package com.mozicoding.spring.velocity;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.ViewToolContext;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

public class VelocityToolboxView extends VelocityView {

	private String toolboxConfigLocation;

	public void setToolboxConfigLocation(String toolboxConfigLocation) {
		this.toolboxConfigLocation = toolboxConfigLocation;
	}

	protected String getToolboxConfigLocation() {
		return this.toolboxConfigLocation;
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected Context createVelocityContext(
			Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

		ServletContext application = this.getServletContext() ;
		VelocityEngine velocityEngine = getVelocityEngine();

		// Create a ChainedContext instance.
		// org.apache.velocity.tools.view.context.ChainedContext velocityContext =
		//		new org.apache.velocity.tools.view.context.ChainedContext( new VelocityContext(model), getVelocityEngine(), request, response, getServletContext());

		ViewToolContext viewToolContext = new ViewToolContext( velocityEngine , request , response , application );
		viewToolContext.putAll( model );

		// Load a Velocity Tools toolbox, if necessary.
		if ( toolboxConfigLocation != null) {

			// 输出 toolboxConfigLocation
			System.out.println( "toolboxConfigLocation : " + toolboxConfigLocation );



			/*
			org.apache.velocity.tools.view.ToolboxManager toolboxManager =
					org.apache.velocity.tools.view.servlet.ServletToolboxManager.getInstance( getServletContext(), toolboxConfigLocation);

			ViewToolManager viewToolManager = new ViewToolManager( getServletContext() );
			ToolboxFactory factory = viewToolManager.getToolboxFactory();

			Map toolboxContext = toolboxManager.getToolbox(velocityContext);
			velocityContext.setToolbox(toolboxContext);
			viewToolContext.addToolbox(  );
			*/
		}

		return viewToolContext;
	}

	@Override
	protected void initTool(Object tool, Context velocityContext) throws Exception {
		// Velocity Tools 1.3: a class-level "init(Object)" method.
		Method initMethod = ClassUtils.getMethodIfAvailable(tool.getClass(), "init", Object.class);
		if (initMethod != null) {
			ReflectionUtils.invokeMethod(initMethod, tool, velocityContext);
		}
	}

}